package com.fanrui.code.util.core;

import java.lang.reflect.Array;
import java.util.List;

import org.apache.commons.lang3.RandomUtils;

public class ListUtil {

	/**
	 * 从集合中随机一个返回
	 */
	public static <T> T getRandom4List(List<T> list) {
		if (list != null && list.size() > 0) {
			int size = list.size();
			int randomIndex = RandomUtils.nextInt(0, size);
			return list.get(randomIndex);
		}
		return null;
	}
	
	public static <T> int indexOf(List<T> list, T t) {
		int index = 0;
		for(T et : list) {
			if(et.equals(t)) {
				return index; 
			}
			index++;
		}
		return -1;
	}

	public static <T> T[] splice(final T[] array, int start) {
		if (start < 0)
			start += array.length;

		return splice(array, start, array.length - start);
	}

	@SuppressWarnings("unchecked")
	public static <T> T[] splice(final T[] array, int start, final int deleteCount) {
		if (start < 0)
			start += array.length;

		final T[] spliced = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length - deleteCount);
		if (start != 0)
			System.arraycopy(array, 0, spliced, 0, start);

		if (start + deleteCount != array.length)
			System.arraycopy(array, start + deleteCount, spliced, start, array.length - start - deleteCount);

		return spliced;
	}

	@SuppressWarnings("unchecked")
	public static <T> T[] splice(final T[] array, int start, final int deleteCount, final T... items) {
		if (start < 0)
			start += array.length;

		final T[] spliced = (T[]) Array.newInstance(array.getClass().getComponentType(),
				array.length - deleteCount + items.length);
		if (start != 0)
			System.arraycopy(array, 0, spliced, 0, start);

		if (items.length > 0)
			System.arraycopy(items, 0, spliced, start, items.length);

		if (start + deleteCount != array.length)
			System.arraycopy(array, start + deleteCount, spliced, start + items.length,
					array.length - start - deleteCount);

		return spliced;
	}

}
